package com.micro.magupe.log.config;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import com.micro.magupe.common.bean.DataSourceType;

@Configuration
@EnableTransactionManagement(order = 2)
@MapperScan("com.micro.magupe.log.dao")
public class MyBatisConfig implements TransactionManagementConfigurer{

	@Autowired
	@Qualifier("writeDataSource")
    private DataSource writeDataSource;
	
	@Autowired
	@Qualifier("readDataSource")
	private DataSource readDataSource;
	
	@Override
	public PlatformTransactionManager annotationDrivenTransactionManager() {
		return new DataSourceTransactionManager(routingDataSouceProxy());
	}

	@Bean
    public AbstractRoutingDataSource routingDataSouceProxy() {
		WriteReadRoutingDataSource proxy = new WriteReadRoutingDataSource();  
        Map<Object, Object> targetDataSources = new HashMap<Object, Object>();  
        targetDataSources.put(DataSourceType.write.getType(), writeDataSource);  
        targetDataSources.put(DataSourceType.read.getType(), readDataSource);  
        proxy.setDefaultTargetDataSource(writeDataSource);
        proxy.setTargetDataSources(targetDataSources);
        return proxy;
    }
	
	@Bean
    @ConditionalOnMissingBean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(routingDataSouceProxy());
        bean.setVfs(SpringBootVFS.class);
        bean.setTypeAliasesPackage("com.micro.magupe.log.entity");
        bean.setConfigLocation(new ClassPathResource("/mybatis-config.xml"));
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/**/*.xml"));
        bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);  
        return bean;
    }
	 
}